<template>
  <v-snackbar
    @update:model-value="msgShowChange(i, $event)"
    :style="{ top: computeOffset(index) }"
    :absolute="true"
    :timeout="computeTimeout(i.msg.msg.timeout)"
    location="top"
    max-width="70vw"
    max-height="50vh"
    :color="computeColor(i.msg.msg)"
    v-model="i.show"
    v-for="(i, index) in msgList"
    :key="index"
  >
    <template v-slot:text>
      <div style="max-height: 45vh;overflow: auto; max-width: calc( 60vw - 30px )">
        {{ i.msg.msg.text }}
      </div>
    </template>
    <template v-slot:actions>
      <v-btn color="green" variant="text" @click="msgShowChange(i,i.show = false)"> x </v-btn>
    </template>
  </v-snackbar>
</template>

<script setup lang="ts">
import { addNewMessageLister } from '@/components/messages/message-service'
import type { Msg, MsgEvent } from "@/components/messages/message-types";
import { computed, reactive } from "vue";

// properties
const msgList = reactive<{ show: boolean; msg: MsgEvent }[]>([])

// methods
const listener = (msg: MsgEvent) => {
  msgList.push({ show: true, msg })
}
const computeOffset = (index: number) => {
  const offset = index * 50
  return offset > 500 ? '0px' : `${offset}px`
}
const computeTimeout = (timeout?: number) => {
  if (typeof timeout !== 'number' || timeout <= 0) {
    return -1
  }
  return timeout
}

const computeColor = (msg: Msg) => {
  if (!msg.type){
    return undefined
  }
  return msg.type === 'success' ? 'indigo' : msg.type === 'error' ? 'red' : 'amber'
}
const msgShowChange = (show: any, e: boolean) => {
  if (!e) {
    const index = msgList.findIndex((v) => v === show)
    msgList.splice(index, 1)
  }
}
// other things
addNewMessageLister(listener)
</script>

<style scoped></style>
